var userId = null;
var modelId = null;
var projectType = 0;
var projectName = null;
var projectId = null;

var modeldata = null;
var modelBoxes = [];
var wizardModelBoxes = [];
var wizardModelIndex = 0;
var wizardModelPage = 0;
var projectdata = null;
var projectBoxes = [];
var t_setInterval = null;
var backStageTimer = null;
var tabletimer = null;

function initPage() {
	window.onmouseover = onMouseOver;
	window.onresize = onResize;
	//	userId = window.location.href.split("=")[1];
	$.ajax({
		url: "Sample/getUserId",
		type: 'POST',
		cache: false,
		async: false,
		dataType: "json",
		contentType: "application/json",
		success: function (data) {
			userId = data.respData;
		}
	});
	$("#progressState").loadStep({
		size: "large",
		color: "blue",
		steps: [
			{ title: "新能源", content: "可再生能源运行模拟" },
			{ title: "水电", content: "长期水电运行模拟" },
			{ title: "检修", content: "检修运行模拟" },
			{ title: "日运行", content: "逐日运行模拟" },
			{ title: "计算结果", content: "导入计算结果" }
		]
	});
	$("#progressState").setStep(1);
	$('#btnGoHome').click(function () {
		$('#modelPanel').show();
		$('#projectPanel').hide();
		$('#btnGoHome').hide();
		modelId = null;
	});
	$('#btnCancel').click(function () {
		$('#wizardMask').hide();
		$('#wizardPanel1').hide();
	});
	$('#btnNextStep').click(function () {
		$('#wizardMask').show();
		$('#wizardPanel2').show();
		$('#wizardPanel1').hide();
	});
	$('#btnPrevStep').click(function () {
		$('#wizardMask').hide();
		$('#wizardPanel2').hide();
	});
	$('#btnEditStep').click(function () {
		$('#wizardMask').hide();
		$('#wizardPaneledit').hide();
	});
	$('#btnEditFinish').click(function () {
		$("#inProjectNameEdit")[0].clearError();
		var inProjectNameEdit = $("#inProjectNameEdit")[0].getValue();
		if (RxCommon.isEmpty(inProjectNameEdit)) {
			$("#inProjectNameEdit")[0].setError("请填写工程名！");
			return;
		} else if (inProjectNameEdit.length > 15) {
			$("#inProjectNameEdit")[0].setError("工程名长度超过15！");
			return;
		}
		var inProjectDemoEdit = $("#inProjectDemoEdit")[0].getValue();
		var result = editProject(projectId, inProjectNameEdit, inProjectDemoEdit);
		if (!result || result.error) {
			if (result.itemName === "projectName") {
				$("#inProjectName")[0].setError("工程名已经存在！");
				return;
			} else if (result.itemName === "planName") {
				$("#inPlanName")[0].setError("方案名已经存在！");
				return;
			} else {
				showMsgBox("修改工程失败！", function (type) {
					return true;
				});
				return;
			}
		} else {
			if (selectModelId == modelId) {
				projectdata = getProjectList(userId, modelId, projectType, projectName);
				refreshProjectList(projectdata);
			}
			showMsgBox("修改工程成功！", function (type) {
				projectdata = getProjectList(userId, modelId, projectType, projectName);
				refreshProjectList(projectdata);
				refreshProjectList4Table(projectdata);
				return true;
			});
		}
		$('#wizardMask').hide();
		$('#wizardPaneledit').hide();
	});

	$('#btnFinish').click(function () {
		JyyLoading.start();
		$("#inProjectName")[0].clearError();
		$("#inPlanName")[0].clearError();
		var inProjectName = $("#inProjectName")[0].getValue();
		if (RxCommon.isEmpty(inProjectName)) {
			$("#inProjectName")[0].setError("请填写工程名！");
			JyyLoading.end();
			return;
		} /*else if(inProjectName.length > 15) {
			$("#inProjectName")[0].setError("工程名长度超过15！");
			JyyLoading.end();
			return;
		}*/
		var inProjectDemo = $("#inProjectDemo")[0].getValue();
		var inPlanName = $("#inPlanName")[0].getValue();
		if (RxCommon.isEmpty(inPlanName)) {
			$("#inPlanName")[0].setError("请填写方案名！");
			JyyLoading.end();
			return;
		} /*else if(inPlanName.length > 15) {
			$("#inPlanName")[0].setError("方案名长度超过15！");
			JyyLoading.end();
			return;
		}*/
		var inPlanDemo = $("#inPlanDemo")[0].getValue();
		var modelProjectDemo = $("#modelProjectDemo option:selected").val()
		$.when(createProject(userId, selectModelId, inProjectName, inProjectDemo, inPlanName, inPlanDemo, modelProjectDemo)).done(function (result) {
			if (!result || result.error) {
				if (result.itemName === "projectName") {
					$("#inProjectName")[0].setError("工程名已经存在！");
				} else if (result.itemName === "planName") {
					$("#inPlanName")[0].setError("方案名已经存在！");
				} else {
					showMsgBox("新建工程失败！", function (type) {
						return true;
					});
				}
			} else {
				if (selectModelId == modelId) {
					projectdata = getProjectList(userId, modelId, projectType, projectName);
					refreshProjectList(projectdata);
				}
				$('#wizardMask').hide();
				$('#wizardPanel2').hide();
				showMsgBox("新建工程成功！", function (type) {
					return true;
				});
			}
			JyyLoading.end();
		});
	});

	$("#btnSearch").find(".gopt_edit_btn").click(function () {
		projectName = $("#btnSearch").find(".gopt_edit_input")[0].value;
		projectdata = getProjectList(userId, modelId, projectType, projectName);
		refreshProjectList(projectdata);
	});
	initSystem();
	modeldata = getModelList();
	refreshModelList(modeldata);
	refreshWizardModelList(modeldata);
	//projectdata = getProjectList(userId, modelId, projectType, projectName);
	//refreshProjectList(projectdata);
	onResize();
	initCommonEvent();
	projectdata = getProjectList(userId, modelId, projectType, projectName);
	//refreshProjectList(projectdata);
	refreshProtasktList();
	refreshProtasktHList();
	$('#progressListClose').click(function () {
		backStageTimer && clearInterval(backStageTimer);
		tabletimer && clearInterval(tabletimer);
		$('#progressList').hide();
	});
	$('#listqueryH').click(function () {
		refreshProtasktHList();
	});
	$('#listclearH').click(function () {
		$('#H_modelName').val("");
		$('#H_projectName').val("");
		$('#H_planName').val("");
	});
	$('#listquery').click(function () {
		$('#backstageText').html("");
		backStageTimer && clearInterval(backStageTimer);
		tabletimer && clearInterval(tabletimer);
		refreshProtasktList();
	});
	$('#listclear').click(function () {
		$('#L_modelName').val("");
		$('#L_projectName').val("");
		$('#L_planName').val("");
	});


	$('#newPro').click(function () {
		$("#inProjectName")[0].setValue("");
		$("#inProjectDemo")[0].setValue("");
		$("#inPlanName")[0].setValue("");
		$("#inPlanDemo")[0].setValue("");
		$('#wizardMask').show();
		initPlanList();
		$('#wizardPanel2').show();
	});
	$('#kapian').click(function () {
		$('#kapian').removeClass('btnomarl');
		$('#kapian').addClass('btclicked');
		$('#liebiao').removeClass('btclicked');
		$('#liebiao').addClass('btnomarl');
		$('#projectListPanel').css('display', 'block');
		$('#projectListPanel4Table').css('display', 'none');
	});
	$('#liebiao').click(function () {
		$('#kapian').removeClass('btclicked');
		$('#kapian').addClass('btnomarl');
		$('#liebiao').removeClass('btnomarl');
		$('#liebiao').addClass('btclicked');
		$('#projectListPanel').css('display', 'none');
		$('#projectListPanel4Table').css('display', 'block');
	});

	/*var flg = sessionStorage.getItem("framsDis"); 
	if(flg=='none'){
		$("#mainFrame").css('display','block');
		$("#body").css('display','none');
	}else{
		$("#mainFrame").css('display','none');
		$("#body").css('display','block');
	}
	sessionStorage.setItem("framsDis", 'none');
	var mapFlag = getQueryString('mapFlag');
	if(mapFlag!=null){
		$("#mainFrames").attr('src','mapData.html');
	}
	$('#btnGoHome').hide();*/
};
function initSystem() {
	var data = invoke_sys('getSystem', { sys: 1 }).respData;
	if (data.data.length > 0) {
		if (data.data[0].sys_mid_index == null) {
			$("#mainFrame").css('display', 'none');
		} else {
			onModelClick();
			$("#mainFrame").css('display', 'none');
			$("#body").css('display', 'block');
			$('#btnGoHome').hide();
		}

	} else {
		//window.parent.location.href = "login.html";
	}
}
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	return r ? unescape(r[2]) : null;
}

function onResize(e) {
	console.log("onResize");
	resizeModelList();
	resizeSearch();
	resizeProjectList();
	resizeMsgBox();
	resizeWizard();
};
function resizeSearch() {
	var panelWidth = $("#projectPanel").width();
	var input = $("#btnSearch").find(".gopt_edit_input")[0];
	var tip = $("#btnSearch").find(".gopt_edit_tip")[0];
	if (panelWidth > (584 + 180 + 160)) {
		$("#btnSearch").css("left", ((panelWidth - 650) / 2) - 40 + "px");
		$("#btnSearch").css("width", "650px");
		$(input).css("width", "584px");
		$(tip).css("width", "584px");
	} else {
		var btnWidth = panelWidth - 180 - 160
		$("#btnSearch").css("left", "180px");
		$("#btnSearch").css("width", (btnWidth) + "px");
		$(input).css("width", (btnWidth - 26) + "px");
		$(tip).css("width", (btnWidth - 26) + "px");
	}
};
function onMouseOver(e) {
	var event = e || window.event;
	var target = event.target;
	if (target.id == "menuProject") {
		$("#menuProjectIcon").css("background-image", "url(../images/menu_expand.png)");
		var top = $(target).offset().top + $(target).height();
		var left = $(target).offset().left;
		$("#menu").css("top", (top + 3) + "px");
		$("#menu").css("left", left + "px");
		$("#menu").show();
	} else if (target.id != "menuProjectLine" && target.className != "gopt_sub_menu") {
		$("#menuProjectIcon").css("background-image", "url(../images/menu_normal.png)");
		$("#menu").hide();
	}
};

function refreshModelList(data) {
	var model = $('#modelPanel')[0];
	var interval = parseInt(($('#modelPanel').width() - 180 - 160 - 5 * 200) / 4);
	var hr = RxCommon.ce(model, null, "hr", "gopt_hr");
	var text_gopt = RxCommon.ce(model, null, "div", "gopt_fonts");
	var text_meos = RxCommon.ce(model, null, "div", "gopt_fonts");
	var pState = 0; // 电力系统菜单情况
	var zState = 0; // 综合能源系统菜单情况
	for (var i = 0; i < data.length; i++) {
		if (data[i].title == "电力系统" && data[i].ifOnClick == 1) {
			pState = 1;
		} else if (data[i].title == "综合能源系统" && data[i].ifOnClick == 1) {
			zState = 1;
		}
	}
	if (pState == 1 && zState == 1) {
		text_gopt.innerHTML = "电力系统";
		text_gopt.style.top = "25px";
		text_meos.innerHTML = "综合能源系统";
		text_meos.style.top = "326px";
	} else if (pState == 1 && zState == 0) {
		text_gopt.innerHTML = "电力系统";
		text_gopt.style.top = "25px";
	} else if (pState == 0 && zState == 1) {
		text_meos.innerHTML = "综合能源系统";
		text_meos.style.top = "25px";
	}
	var powerleft = 180; // 电力系统位置
	var compleft = 180; // 综合能源系统位置

	for (var i = 0; i < data.length; i++) {
		if (data[i] == undefined || data[i] == null) return;
		if (data[i].ifOnClick == 0) continue;
		var box = RxCommon.ce(model, null, "div", "gopt_big_box");
		box.data = data[i];
		if (data[i].title == "电力系统") {
			box.style.top = "53px";
			box.style.left = powerleft + "px";
			powerleft = (powerleft + 190 + interval);
		} else if (data[i].title == "综合能源系统" && pState == 0) {
			box.style.top = "53px";
			box.style.left = compleft + "px";
			compleft = (compleft + 190 + interval);
		} else if (data[i].title == "综合能源系统" && pState == 1) {
			box.style.top = "373px";
			box.style.left = compleft + "px";
			compleft = (compleft + 190 + interval);
		}
		box.onclick = onModelClick;
		var icon = RxCommon.ce(box, null, "img", null);
		icon.src = data[i].image;
		icon.style.width = "150px";
		icon.style.height = "150px";
		var text = RxCommon.ce(box, null, "div", null);
		text.style.width = "160px";
		text.innerHTML = data[i].name;
		modelBoxes[i] = box;
	}
};
function resizeModelList() {
	var model = $('#modelPanel')[0];
	var interval = parseInt(($('#modelPanel').width() - 180 - 160 - 5 * 200) / 4);
	/*for (var i = 0; i < modelBoxes.length; i++) {
		modelBoxes[i].style.top = (53 + Math.floor(i/5)*(300+20)) + "px";
		modelBoxes[i].style.left = (180 + Math.floor(i%5)*(200+interval)) + "px";
	}*/
};
function resizeProjectList() {
	var projects = $('#projectListPanel')[0];
	var panelWidth = $('#projectListPanel').width() - 6;
	var interval = 0;
	var colCount = Math.floor((panelWidth + interval) / (180 + interval));
	if (colCount <= 1) {
		interval = 0;
	} else {
		interval = (panelWidth - colCount * 180) / (colCount - 1);
	}
	for (var i = 0; i < projectBoxes.length; i++) {
		projectBoxes[i].style.top = (Math.floor(i / colCount) * (210 + 10)) + "px";
		projectBoxes[i].style.left = (Math.floor(i % colCount) * (180 + interval)) + "px";
	}

};

var model = null;
function refreshWizardModelList(data) {
	var model = $('#btnInnerPanel')[0];
	var interval = 87;
	model.style.left = "0px";
	model.style.width = (interval * data.length + 35) + "px";
	for (var i = 0; i < data.length; i++) {
		var box = RxCommon.ce(model, null, "div", "gopt_box");
		box.data = data[i];
		box.style.left = (i * interval) + "px";
		box.index = i;
		box.onclick = onModelSelect;
		wizardModelBoxes[i] = box;

		var active = RxCommon.ce(box, null, "div", "gopt_box");
		active.style.display = "none";
		box.active = active;
		var normal = RxCommon.ce(box, null, "div", "gopt_box");
		normal.style.display = "block";
		box.normal = normal;

		var activebg = RxCommon.ce(active, null, "img", "gopt_box_bg_active");
		activebg.src = "../images/model_bg_active.png";
		var activeicon = RxCommon.ce(active, null, "img", "gopt_box_icon");
		activeicon.src = data[i].wizarIconActive;

		var normalbg = RxCommon.ce(normal, null, "img", "gopt_box_bg_normal");
		normalbg.src = "../images/model_bg_normal.png";
		var normalicon = RxCommon.ce(normal, null, "img", "gopt_box_icon");
		normalicon.src = data[i].wizarIconNormal;
	}

	//wizardModelBoxes[2].click();
};

function refreshProjectList4Table(data) {
	var tableData = [];
	for (var i = 0; i < data.length; i++) {
		tableData.push({
			"id": data[i].id, "name": data[i].name, "username": '用户名：' + data[i].username, "datedata": '创建时间：' + data[i].createTime, "demo": data[i].demo, "isShared": data[i].isShared
			, "modelId": data[i].modelId, "modelName": data[i].modelName
		})
	}
	layui.use('table', function () {
		var table = layui.table;

		table.render({
			elem: '#test'
			, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
				title: '提示'
				, layEvent: 'LAYTABLE_TIPS'
				, icon: 'layui-icon-tips'
			}]
			, title: '用户数据表'
			, cols: [[/*
		    		{fixed: 'isShared', title:'状态',templet:'<div><img  src="../images/project_share_active.png"></div>', width:90},*/
				{
					field: 'isShared', title: '状态', width: 90, templet: function (d) {
						let result = "";
						if (d.isShared) {
							result = '<div><img  src="../images/project_share_active.png"></div>'
						}
						return result;
					}
				},
				{ field: 'id', title: '工程名称', hide: true, align: 'center' },
				{ field: 'name', title: '工程名称', width: '20%', align: 'center' },
				{ field: 'username', title: '用户名', width: '15%', align: 'center' },
				{ field: 'datedata', title: '创建时间', width: '20%', align: 'center' },
				{ field: 'demo', title: 'demo', width: '20%', hide: true, align: 'center' },/*
			    	{fixed: 'right', title:'操作', toolbar: '#barDemo', width:'40%',align: 'center'},*/
				{
					field: 'cz', title: '操作', width: '45%', templet: function (d) {
						let result = "";
						if (d.isShared) {
							result = '<a class="layui-btn layui-btn-xs" lay-event="edit"  style="background-color: #557DFF;width: 60px;">编辑</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="save"  style="background-color: #FF9933;width: 60px;">另存为</a>'
								+ '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"  style="background-color: #FF4D4F;width: 60px;">删除</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="unshare"  style="background-color: #00CC99;width: 60px;">取消共享</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="into"  style="background-color: #9966FF;width: 60px;">进入</a>'
							/*+'<a class="layui-btn layui-btn-xs" lay-event="state"  style="background-color: #9966FF;width: 60px;">计算进度</a>'
							+'<a class="layui-btn layui-btn-xs" lay-event="kill"  style="background-color: #9966FF;width: 60px;">强制关闭</a>'*/
						} else {
							result = '<a class="layui-btn layui-btn-xs" lay-event="edit"  style="background-color: #557DFF;width: 60px;">编辑</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="save"  style="background-color: #FF9933;width: 60px;">另存为</a>'
								+ '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"  style="background-color: #FF4D4F;width: 60px;">删除</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="share"  style="background-color: #00CC99;width: 60px;">共享</a>'
								+ '<a class="layui-btn layui-btn-xs" lay-event="into"  style="background-color: #9966FF;width: 60px;">进入</a>'
							/*+'<a class="layui-btn layui-btn-xs" lay-event="state"  style="background-color: #9966FF;width: 60px;">计算进度</a>'
							+'<a class="layui-btn layui-btn-xs" lay-event="kill"  style="background-color: #9966FF;width: 60px;">强制关闭</a>'*/
						}
						return result;
					}
				},
			]]
			, data: tableData
			, even: true
			, page: true
		});
		//监听行工具事件
		table.on('tool(test)', function (obj) {
			var data = obj.data;
			if (obj.event === 'del') {
				layer.confirm('确认删除么？', function (index) {
					onDeleteProject(data);

					projectName = $("#btnSearch").find(".gopt_edit_input")[0].value;
					projectdata = getProjectList(userId, data.modelId, projectType, projectName);
					refreshProjectList(projectdata);
					refreshProjectList4Table(projectdata);
					layer.close(index);
				});
			} else if (obj.event === 'save') {
				$("#wizardMask").show();
				showConfirmMsgBox("确定新建此工程副本吗？", function (type) {
					$("#wizardMask").hide();
					if (type == "cancel") {
						return;
					}
					var result = onCopyProject(data);
					if (!result || result.error) {
						showMsgBox("新建工程副本失败！", function (type) {
							return true;
						});
					} else {
						showMsgBox("新建工程副本成功！", function (type) {
							projectName = $("#btnSearch").find(".gopt_edit_input")[0].value;
							projectdata = getProjectList(userId, modelId, projectType, projectName);
							refreshProjectList(projectdata);
							refreshProjectList4Table(projectdata);
							return true;
						});
					}
				});
			} else if (obj.event === 'edit') {
				intProjectInfo(data);
				$("#wizardMask").show();
				$("#wizardPaneledit").show();

			} else if (obj.event === 'unshare' || obj.event === 'share') {
				$("#wizardMask").show();
				showConfirmMsgBox(data.isShared ? "确定要取消共享吗？" : "确定要共享吗？", function (type) {
					$("#wizardMask").hide();
					if (type == "cancel") {
						return;
					}
					data.isShared = !data.isShared;
					var result = onShareProject(data);
					if (!result || result.error) {
						showMsgBox(data.isShared ? "取消共享失败！" : "共享失败！", function (type) {
							return true;
						});
					} else {
						projectdata = getProjectList(userId, modelId, projectType, projectName);
						refreshProjectList(projectdata);
						refreshProjectList4Table(projectdata);
					}
				});
			} else if (obj.event === 'into') {
				window.location.href = "../pages/work.html?projectId=" + data.id + "&modelId=" + data.modelId;
			} else if (obj.event === 'state') {
				//getProState(data.id);

				$('#progressClose').click(function () {
					$('#progressDiv').hide();
					clearInterval(t_setInterval);
				});

				$('#progressDiv').show();
				$('#progressDiv').draggable();

				t_setInterval = setInterval(function () {
					$.ajax({
						dataType: "json",
						data: { planId: data.id },
						url: 'executive/getProgressInfoYX'
					}).done(function (res) {
						var r = eval("(" + res.result + ")");
						$('#progressStrip').css({ width: r.progressBar + "%" });
						$('#progressStrip').find("span").text(r.progressBar + "%");
						$('#progressText').html(r.result);
						$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
						$("#progressState").setStep(r.progressState);
					});
				}, 1000);

			} else if (obj.event === 'kill') {
				killTasklist(data.id);



			}
		});
	});
	$('.layui-table .layui-table-cell > span').css({ 'font-weight': 'bold' });//表头字体样式
	$('th').hide();//表头隐藏的样式

	$('.layui-table-header').css('display', 'none');//页码部分的高度调整
	$('.layui-table-page').css('margin-top', '40px');//页码部分的高度调整
};

function refreshProjectList(data) {
	var projects = $('#projectListPanel')[0];
	projects.innerHTML = "";

	var pro = RxCommon.ce(projects, null, "div", "project_box");
	var bo = RxCommon.ce(pro, null, "div", "project_icon_box");
	var add = RxCommon.ce(bo, "btnCreateProject", "div", "btn_icon");
	var img = RxCommon.ce(add, null, "img", null);
	img.style = "position:absolute;top:8px;left:8px;width:90px;height:90px;";
	img.src = "../images/plan_add.png";
	pro.onclick = function () {
		$("#inProjectName")[0].setValue("");
		$("#inProjectDemo")[0].setValue("");
		$("#inPlanName")[0].setValue("");
		$("#inPlanDemo")[0].setValue("");
		$('#wizardMask').show();
		initPlanList();
		$('#wizardPanel2').show();
	}
	projectBoxes[0] = pro;
	for (var i = 0; i < data.length; i++) {


		var project = RxCommon.ce(projects, null, "div", "project_box");
		var box = RxCommon.ce(project, null, "div", "project_icon_box");
		var icon = RxCommon.ce(box, null, "div", "project_box_icon");
		var shared = RxCommon.ce(box, null, "div", "project_btn_shared_status");
		if (data[i].isShared) {
			shared.style.display = "block";
		}
		var opbox = RxCommon.ce(box, null, "div", "project_box_op_panel");
		var deleteBtn = RxCommon.ce(opbox, null, "div", "project_btn_delete");
		var shareBtn = RxCommon.ce(opbox, null, "div", "project_btn_unshared");
		var copyBtn = RxCommon.ce(opbox, null, "div", "project_btn_copy");
		var editBtn = RxCommon.ce(opbox, null, "div", "project_btn_edit");

		var deleteBtn_mark = RxCommon.ce(opbox, null, "div", "project_btn_delete_mark");
		var shareBtn_mark = RxCommon.ce(opbox, null, "div", "project_btn_unshared_mark");
		var copyBtn_mark = RxCommon.ce(opbox, null, "div", "project_btn_copy_mark");
		var editBtn_mark = RxCommon.ce(opbox, null, "div", "project_btn_edit_mark");
		$(".project_btn_delete_mark").text("删除");
		$(".project_btn_unshared_mark").text("共享");
		$(".project_btn_copy_mark").text("另存为");
		$(".project_btn_edit_mark").text("编辑");

		if (data[i].isShared) {
			shareBtn.className = "project_btn_shared";
		}
		var text = RxCommon.ce(project, null, "div", "project_box_text");
		text.innerHTML = data[i].name + "<br/><font size=3 color='#999999'>" + data[i].createTime + "</font>"


		project.data = shareBtn.data = deleteBtn.data = copyBtn.data = data[i] = editBtn.data = data[i];;

		project.onclick = function () {
			console.log("box click");
			window.location.href = "../pages/work.html?projectId=" + this.data.id + "&modelId=" + this.data.modelId;
		};
		deleteBtn.onclick = function () {
			console.log(this.data);
			var e = e || window.event;
			e.cancelBubble = true;
			e.stopPropagation();
			var data = this.data;
			$("#wizardMask").show();
			showConfirmMsgBox("该工程下方案也会删除，确定要删除吗？", function (type) {
				$("#wizardMask").hide();
				if (type == "cancel") {
					return;
				}
				JyyLoading.start();
				$.when(onDeleteProject(data)).done(function (result) {
					JyyLoading.end();
					if (!result || result.error) {
						showMsgBox("删除失败！", function (type) {
							return true;
						});
					} else {
						showMsgBox("删除成功！", function (type) {
							projectName = $("#btnSearch").find(".gopt_edit_input")[0].value;
							projectdata = getProjectList(userId, modelId, projectType, projectName);
							refreshProjectList(projectdata);
							return true;
						});
					}
					JyyLoading.end();
				});
			});
		};

		copyBtn.onclick = function () {
			console.log(this.data);
			var e = e || window.event;
			e.cancelBubble = true;
			e.stopPropagation();
			var data = this.data;
			$("#wizardMask").show();
			showConfirmMsgBox("确定新建此工程副本吗？", function (type) {
				$("#wizardMask").hide();
				if (type == "cancel") {
					return;
				}
				var result = onCopyProject(data);
				if (!result || result.error) {
					showMsgBox("新建工程副本失败！", function (type) {
						return true;
					});
				} else {
					showMsgBox("新建工程副本成功！", function (type) {
						projectName = $("#btnSearch").find(".gopt_edit_input")[0].value;
						projectdata = getProjectList(userId, modelId, projectType, projectName);
						refreshProjectList(projectdata);
						return true;
					});
				}
			});
		};

		editBtn.onclick = function () {
			console.log(this.data);
			var e = e || window.event;
			e.cancelBubble = true;
			e.stopPropagation();
			var data = this.data;
			intProjectInfo(data);
			$("#wizardMask").show();
			$("#wizardPaneledit").show();
		};


		shareBtn.status = shared;
		shareBtn.onclick = function () {
			console.log(this.data);
			var e = e || window.event;
			e.cancelBubble = true;
			e.stopPropagation();
			var self = this;
			var data = self.data;
			var status = self.status;
			$("#wizardMask").show();
			showConfirmMsgBox(data.isShared ? "确定要取消共享吗？" : "确定要共享吗？", function (type) {
				$("#wizardMask").hide();
				if (type == "cancel") {
					return;
				}
				data.isShared = !data.isShared;
				var result = onShareProject(data);
				if (!result || result.error) {
					showMsgBox(data.isShared ? "取消共享失败！" : "共享失败！", function (type) {
						return true;
					});
				} else {
					if (data.isShared) {
						status.style.display = "block";
						self.className = "project_btn_shared";
					} else {
						status.style.display = "none";
						self.className = "project_btn_unshared";
					}
				}
			});
		};
		project.op = opbox;
		project.onmouseover = function () {
			this.op.style.display = "block";
		};
		project.onmouseout = function () {
			this.op.style.display = "none";
		};

		deleteBtn.onmouseover = function () {
			$(".project_btn_delete_mark").css('display', 'block');
		};
		deleteBtn.onmouseout = function () {
			$(".project_btn_delete_mark").css('display', 'none');
		};

		shareBtn.onmouseover = function () {
			$(".project_btn_unshared_mark").css('display', 'block');
		};
		shareBtn.onmouseout = function () {
			$(".project_btn_unshared_mark").css('display', 'none');
		};

		copyBtn.onmouseover = function () {
			$(".project_btn_copy_mark").css('display', 'block');
		};
		copyBtn.onmouseout = function () {
			$(".project_btn_copy_mark").css('display', 'none');
		};

		editBtn.onmouseover = function () {
			$(".project_btn_edit_mark").css('display', 'block');
		};
		editBtn.onmouseout = function () {
			$(".project_btn_edit_mark").css('display', 'none');
		};
		projectBoxes[i + 1] = project;
		if (i == data.length - 1) {

		}
	}

	resizeProjectList();
};

function onDeleteProject(data) {
	var defer = $.Deferred();
	$.ajax({
		//async: false,
		dataType: "json",
		data: { projectId: data.id },
		url: "main/deleteProjrct"
	}).done(function (res) {
		defer.resolve(eval("(" + res.result + ")"));
	});
	return defer.promise();
};

function onCopyProject(data) {
	var result = null;
	$.ajax({
		async: false,
		dataType: "json",
		data: { projectId: data.id, typeId: data.modelId },
		url: "main/copyProjrct"
	}).done(function (res) {
		result = eval("(" + res.result + ")");
	});

	return result;
};

function onShareProject(data) {
	var result = null;
	$.ajax({
		async: false,
		dataType: "json",
		data: { projectId: data.id, isShared: data.isShared },
		url: "main/shareProject"
	}).done(function (res) {
		result = eval("(" + res.result + ")");
	});
	return result;
};

function onMenuClick(flag) {
	console.log(flag);
	if (flag == 5) {
		return;
	}
	if (modelId == null) {
		return;
	}
	if (flag == 3) {
		if (userCode != 0) return;
		$('#newPro').css('display', 'none');
	} else if (flag == 4) {
		return;
	} else {
		$('#newPro').css('display', 'inline');
	}
	$('#projectPanel').show();
	$('#btnGoHome').show();
	$('#modelPanel').hide();
	projectType = flag;
	projectName = null;
	$("#btnSearch").find(".gopt_edit_input")[0].value = null;
	projectdata = getProjectList(userId, modelId, projectType, projectName);
	refreshProjectList(projectdata);
	refreshProjectList4Table(projectdata);
}
function onModelClick() {
	//console.log(this.data);
	if (this.data != undefined && this.data.id == 3) {
		$("#mainFrame").css('display', 'block');
		$("#body").hide();
		$("#mainFrames").attr('src', 'mapData.html');
	} else {
		$('#projectPanel').show();
		$('#btnGoHome').show();
		$('#modelPanel').hide();
		if (this.data) {
			modelId = this.data.id;
			selectModelId = this.data.id;
		} else {
			modelId = 0;
			selectModelId = 0;
		}
		projectType = 0;
		projectName = null;
		$("#btnSearch").find(".gopt_edit_input")[0].value = null;
		projectdata = getProjectList(userId, modelId, projectType, projectName);
		refreshProjectList(projectdata);
		refreshProjectList4Table(projectdata);
	}
}
function onModelClick4Table() {
	console.log(this.data);
	$('#projectPanel').show();
	$('#btnGoHome').show();
	$('#modelPanel').hide();
	modelId = this.data.id;
	selectModelId = this.data.id;
	projectType = 0;
	projectName = null;
	$("#btnSearch").find(".gopt_edit_input")[0].value = null;
	projectdata = getProjectList(userId, modelId, projectType, projectName);
	refreshProjectList(projectdata);
}


var selectModelId = null;
function onModelSelect() {
	console.log(this.data);
	wizardModelIndex = this.index;
	//selectModelId = this.data.id;
	var findIndex = -1;
	for (var i = 0; i < wizardModelBoxes.length; i++) {
		if (wizardModelBoxes[i] == this) {
			wizardModelBoxes[i].active.style.display = "block";
			wizardModelBoxes[i].normal.style.display = "none";
			wizardModelBoxes[i].style.zIndex = 100;
			$("#imgModelDemo").attr("src", this.data.wizarImage);
			$("#txtModelTitle").html(this.data.name);
			$("#txtModelHead").html(this.data.title);
			$("#txtModelTrait").html(this.data.trait);
			findIndex = i;
		} else {
			wizardModelBoxes[i].active.style.display = "none";
			wizardModelBoxes[i].normal.style.display = "block";
			if (findIndex === -1) {
				wizardModelBoxes[i].style.zIndex = i;
			} else {
				wizardModelBoxes[i].style.zIndex = (100 - (i - findIndex));
			}
		}
	}
	$("#btnArrowLeft").click(function () {
		onModelReturnPage(-1);
	});
	$("#btnArrowRight").click(function () {
		onModelReturnPage(1);
	});
	onModelReturnPage(0);
}

function onModelReturnPage(count) {
	var pageIndex = wizardModelPage + count;
	var isReturn = false;
	var model = $('#btnInnerPanel')[0];
	var interval = 87;
	if (pageIndex <= 0) {
		$("#btnArrowLeft").addClass("gopt_arrow_alpha");
		if (pageIndex < 0) {
			isReturn = true;
		}
	} else if (pageIndex > 0) {
		$("#btnArrowLeft").removeClass("gopt_arrow_alpha");
	}
	if ((pageIndex + 5) >= wizardModelBoxes.length) {
		$("#btnArrowRight").addClass("gopt_arrow_alpha");
		if ((pageIndex + 5) > wizardModelBoxes.length) {
			isReturn = true;
		}
	} else if ((pageIndex + 5) < wizardModelBoxes.length) {
		$("#btnArrowRight").removeClass("gopt_arrow_alpha");
	}
	if (isReturn) {
		return;
	}
	wizardModelPage = pageIndex;
	model.style.left = (-pageIndex * interval) + "px";
}

function resizeWizard() {
	var panel = $('#viewPanel')[0];
	var panelWidth = $('#viewPanel').width();
	var panelHeight = $('#viewPanel').height();
	$('#wizardPanel1').css({ top: ((panelHeight - 500) / 2) + "px", left: ((panelWidth - 600) / 2) + "px" });
	$('#wizardPanel2').css({ top: ((panelHeight - 500) / 2) + "px", left: ((panelWidth - 600) / 2) + "px" });
}

function initPlanList() {
	var sel = $('#modelProjectDemo');
	var method = 'getModelProject';
	invoke(method, { modelId: modelId }, function (data) {
		var list = data.respData;
		sel.empty();
		for (var i = 0; i < list.length; i++) {
			if (list[i].id == 0) continue;
			sel.append('<option value="' + list[i].id + '">' + list[i].name + '</option>');
		}
		sel.selectpicker('refresh');
	});
};
function intProjectInfo(data) {
	var method = 'getProjectInfo';
	projectId = data.id;
	invoke(method, { projectId: data.id }, function (data) {
			if (data.respData[0].name != undefined) {
				$("#inProjectNameEdit")[0].setValue(data.respData[0].name);
			}
			$("#inProjectDemoEdit")[0].setValue("");
			if (data.respData[0].demo != undefined) {
				$("#inProjectDemoEdit")[0].setValue(data.respData[0].demo);
			}
		}
	);
};
function getProState(projectId) {
	var method = 'getProState';
	invoke(method, { modelId: modelId, projectId: projectId }, function (data) {
			$("#progressState").loadStep({
				size: "large",
				color: "blue",
				steps: [
					{ title: "新能源", content: "可再生能源运行模拟" },
					{ title: "水电", content: "长期水电运行模拟" },
					{ title: "检修", content: "检修运行模拟" },
					{ title: "日运行", content: "逐日运行模拟" },
					{ title: "计算结果", content: "导入计算结果" }
				]
			});
			$("#progressState").setStep(1);


			$('#progressDiv').show();
			$('#progressDiv').draggable();
			var r = eval("(" + data.outInfo + ")");
			$('#progressStrip').css({ width: r.progressBar + "%" });
			$('#progressStrip').find("span").text(r.progressBar + "%");
			$('#progressText').html(r.result);
			$('#progressText')[0].scrollTop = $('#progressText')[0].scrollHeight;
			$("#progressState").setStep(r.progressState);


		}
	);
};

function killTasklist(projectId) {
	var method = 'killTasklist';
	invoke(method, { modelId: modelId, projectId: projectId }, function (data) {


		}
	);
};
function killNowTask(taskid) {
	var method = 'killNowTask';
	invoke(method, { modelId: modelId, taskid: taskid }, function (data) {
		}
	);
};
function killTasklist(taskid) {
	var method = 'killTasklist';
	invoke(method, { modelId: modelId, taskid: taskid }, function (data) {
		refreshProtasktList();
	});
};
function delWaitTask(taskid) {
	var method = 'delWaitTask';
	invoke(method, { modelId: modelId, taskid: taskid }, function (data) {
		refreshProtasktList();
	});
};
function showProPanl() {
	refreshProtasktList();
	refreshProtasktHList();
	$('#progressList').show();
	$('#progressList').draggable({ cancel: "div[lay-filter='docDemoTabBrief']" });
};
function refreshProtasktList() {
	var tableData = [];
	var L_modelName = $('#L_modelName').val();
	var L_projectName = $('#L_projectName').val();
	var L_planName = $('#L_planName').val();
	if (L_modelName == '模块名称') {
		L_modelName = '';
	}
	if (L_projectName == '工程名称') {
		L_projectName = '';
	}
	if (L_planName == '方案名称') {
		L_planName = '';
	}
	var data = invoke('getRunList', { modelName: L_modelName, projectName: L_projectName, planName: L_planName }).respData;

	for (var i = 0; i < data.length; i++) {
		tableData.push({
			"sortNo": data[i].sortNo,
			"id": data[i].id,
			"modelName": data[i].modelName,
			"proName": data[i].proName,
			"planName": data[i].planName,
			"starttime": data[i].starttime,
			"state": data[i].state
			, "jd": data[i].jd, "taskid": data[i].taskid
		})
	}
	layui.use(['table', 'element', 'layer'], function () {
		var table = layui.table;
		var element = layui.element;
		var layer = layui.layer;
		var nowCurr = 1;
		var nowCount = 0;
		var tabrender = table.render({
			elem: '#test2',
			width: 1180,
			height: 225
			, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
				title: '提示'
				, layEvent: 'LAYTABLE_TIPS'
				, icon: 'layui-icon-tips'
			}]
			, title: '用户数据表',
			limit: 50
			, cols: [[{ field: 'sortNo', title: '序号', width: '6%', align: 'center' },
				{ field: 'id', title: '工程名称', hide: true, align: 'center' },
				{ field: 'modelName', title: '模块名称', width: '12%', align: 'center' },
				{ field: 'proName', title: '工程名称', width: '13%', align: 'center' },
				{ field: 'planName', title: '方案名称', width: '12%', align: 'center' },
				{ field: 'starttime', title: '启动时间', width: '15%', align: 'center' },
				{ field: 'state', title: '状态', width: '9%', align: 'center' },/*
			    	{fixed: 'right', title:'操作', toolbar: '#barDemo', width:'40%',align: 'center'},*/
				{
					field: 'jd', title: '计算进度', width: '25%', align: 'center', templet: function (d) {
						var hp = 0;
						if (d.modelName == '源网储一体化规划') {
							hp = 50 * d.jd;
						} else {
							hp = 0.14 * d.jd;
							hp = hp.toFixed(1);
							hp = hp * 100;
						}
						if (hp > 100) {
							hp = 100;
						}
						let result = "";
						if (d.state == '正在计算' && d.modelName == '调度运行模拟') {
							result = '<div class="layui-progress layui-progress-big" lay-filter="progress0" lay-showpercent="true"><div class="layui-progress-bar layui-bg-orange" lay-percent="' + hp + '%"></div></div><br>';
						} else if (d.state == '正在计算' && d.modelName == 'dat转换') {
							result = '<div class="layui-progress layui-progress-big" lay-filter="progress100" lay-showpercent="true"><div class="layui-progress-bar layui-bg-orange" lay-percent="' + hp + '%"></div></div><br>';
						} else if (d.state == '正在计算' && d.modelName == '源网储一体化规划') {
							result = '<div class="layui-progress layui-progress-big" lay-filter="progress2" lay-showpercent="true"><div class="layui-progress-bar layui-bg-orange" lay-percent="' + hp + '%"></div></div><br>';
						} else {
							result = '<div class="layui-progress layui-progress-big"   lay-showpercent="true"><div class="layui-progress-bar layui-bg-orange" lay-percent="' + hp + '%"></div></div><br>';
						}
						return result;
					}
				},
				{
					field: 'cz', title: '操作', width: '8%', templet: function (d) {
						let result = "";
						if (d.state == '正在计算') {
							result = '<a class="layui-btn layui-btn-xs" lay-event="kill"  style="background-color: #557DFF;width: 60px;color:white;">终止</a>'
						} else {
							result = '<a class="layui-btn layui-btn-xs" lay-event="delpro"  style="background-color: #557DFF;width: 60px;color:white;">删除任务</a>'
						}
						return result;
					}
				}, { field: 'taskid', title: 'taskid', hide: true, align: 'center' },
			]]
			, data: tableData
			, even: true
			, done: function (res, curr, count) {
				//***重点***：table渲染完成后渲染element进度条
				element.render();
				table.render();
				nowCurr = curr;
				nowCount = count;
			}
		});
		tabletimer && clearInterval(tabletimer);
		if (nowCount > 0) {
			tabletimer = setInterval(function () {
				invoke("getProgress", {}, function (data) {
					var d = data.data;
					for (var i = 0; i < d.length; i++) {
						var hp = 0;
						if (d[i].modelId == '2') {
							hp = 50 * d[i].jd;
						} else {
							hp = 0.14 * d[i].jd;
							hp = hp.toFixed(1);
							hp = hp * 100;
						}
						if (hp == 0) {
							$('#listquery')[0].click();
						}
						if (hp > 100 || hp == 100) {
							hp = 100;
							$('#listquery')[0].click();
						}
						element.progress('progress' + d[i].modelId, hp + "%");
					}
					if (d.length == 0) {
						$('#listquery')[0].click();
					}
				})
			}, 2000);
		}
		table.on('row(test2)', function (obj) {
			if (obj.data.state != "正在计算") {
				layer.msg('任务未开始，暂无信息', { icon: 2 });
				return;
			}
			$('#backstageText').html("");
			backStageTimer && clearInterval(backStageTimer);
			var url = "";
			if (obj.data.modelName == "调度运行模拟") {
				url = 'executive/getProgressInfoYX';
			} else if (obj.data.modelName == "源网储一体化规划") {
				url = "executivegtep/getProgressInfoYX";
			} else if (obj.data.modelName == "dat转换") {
				url = "executivedat/getProgressInfo";
			}
			backStageTimer = setInterval(function () {
				$.ajax({
					dataType: "json",
					data: { planId: obj.data.id },
					url: url
				}).done(function (res) {
					var r = eval("(" + res.result + ")");
					$('#backstageText').html(r.result);
					$('#backstageText')[0].scrollTop = $('#backstageText')[0].scrollHeight;
				});
			}, 1000);
		});

		//监听行工具事件
		table.on('tool(test2)', function (obj) {
			var data = obj.data;
			obj.tr.data('off', true);
			if (obj.event === 'delpro') {
				layer.confirm('是否终止计算任务', {
					btn: ['确定', '取消'] //按钮
				}, function () {
					delWaitTask(data.taskid);
					layer.msg('已终止计算任务', { icon: 1 });
				}, function () {
					layer.msg('取消终止计算任务', { icon: 1 });
					obj.tr.data('off', false);
				});
			} else if (obj.event === 'kill') {
				layer.confirm('是否删除计算任务', {
					btn: ['确定', '取消'] //按钮
				}, function () {
					$('#backstageText').html("");
					killTasklist(data.taskid);
					backStageTimer && clearInterval(backStageTimer);
					//					tabletimer && clearInterval(tabletimer);
					layer.msg('已删除计算任务', { icon: 1 });
				}, function () {
					layer.msg('取消除计算任务', { icon: 1 });
					obj.tr.data('off', false);
				});
			}
		});
	});
};
function refreshProtasktHList() {
	var tableData1 = [];
	var H_modelName = $('#H_modelName').val();
	var H_projectName = $('#H_projectName').val();
	var H_planName = $('#H_planName').val();
	if (H_modelName == '模块名称') {
		H_modelName = '';
	}
	if (H_projectName == '工程名称') {
		H_projectName = '';
	}
	if (H_planName == '方案名称') {
		H_planName = '';
	}
	var data1 = invoke('getRunLog', { modelName: H_modelName, projectName: H_projectName, planName: H_planName }).respData;

	for (var i = 0; i < data1.length; i++) {
		tableData1.push({
			"sortNo": data1[i].sortNo,
			"id": data1[i].id,
			"modelName": data1[i].modelName,
			"proName": data1[i].proName,
			"planName": data1[i].planName,
			"starttime": data1[i].starttime,
			"endtime": data1[i].endtime,
			"state": data1[i].state
			, "jd": data1[i].jd
		})
	}
	layui.use(['table', 'element'], function () {
		var table = layui.table;
		var element = layui.element;

		table.render({
			elem: '#test1',
			width: 1180,
			height: 435
			, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
				title: '提示'
				, layEvent: 'LAYTABLE_TIPS'
				, icon: 'layui-icon-tips'
			}]
			, title: '用户数据表'
			, cols: [[{ field: 'sortNo', title: '序号', width: '8%', align: 'center' },
				{ field: 'id', title: '工程名称', hide: true, align: 'center' },
				{ field: 'modelName', title: '模块名称', width: '15%', align: 'center' },
				{ field: 'proName', title: '工程名称', width: '15%', align: 'center' },
				{ field: 'planName', title: '方案名称', width: '12%', align: 'center' },
				{ field: 'starttime', title: '启动时间', width: '20%', align: 'center' },
				{ field: 'endtime', title: '结束时间', width: '20%', align: 'center' },
				{ field: 'state', title: '状态', width: '9.5%', align: 'center' },
			]]
			, data: tableData1
			, even: true
			, page: true
			, done: function (res, currentCount) {
				//***重点***：table渲染完成后渲染element进度条
				element.render();
				table.render();
			}
		});
	});
};



function invoke(url, args, callback) {
	var r, op = {
		url: 'Sample/' + url,
		type: 'POST',
		cache: false,
		async: true,
		dataType: 'json',
		data: args ? JSON.stringify(args) : null,
		contentType: "application/json"
	};
	if (typeof callback == 'function') {
		op.success = function (data) {
			if (data.error) return alert(data.error);
			callback(data);
		}
	} else {
		op.async = false;
		op.success = function (data) {
			r = data
		};
	}
	$.ajax(op);
	if (r) if (r.error) {
		alert(r.error);
		return null;
	}
	return r;
};
function invoke_sys(url, args, callback) {
	var r, op = {
		url: 'Sysconfig/' + url,
		type: 'POST',
		cache: false,
		async: true,
		dataType: 'json',
		data: args ? JSON.stringify(args) : null,
		contentType: "application/json"
	};
	if (typeof callback == 'function') {
		op.success = function (data) {
			if (data.error) return alert(data.error);
			callback(data);
		}
	} else {
		op.async = false;
		op.success = function (data) {
			r = data
		};
	}
	$.ajax(op);
	if (r) if (r.error) {
		alert(r.error);
		return null;
	}
	return r;
};